package com.thermofisher.controller;

import com.thermofisher.beans.Employee;
import com.thermofisher.mapper.EmployeeMapper;
import com.thermofisher.utils.Result;
import org.apache.commons.codec.binary.Base64;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.List;

@RestController
public class TokenController
{

    private static final Logger log = LoggerFactory.getLogger(TokenController.class);

    public static final String CHARSET = "UTF-8";

    public static final String RSA_ALGORITHM = "RSA";

    public static final String SIGNATURE_ALGORITHM = "SHA1WithRSA";

    @Autowired
    private EmployeeMapper employeeMapper;

    @Value("${home.url}")
    private String url;

    @Value("${home.publicKey}")
    private String publicKey;

    final Base64 base64 = new Base64();

    @GetMapping("/getEmail")
    public Result checkToken(@Param("token") String token, @Param("email") String email,
                             @Param("ts") String ts)
    {
        Result result = new Result();
        boolean bverify = verify(token, email, ts);
        if (bverify)
        {
            result.setCode(String.valueOf(HttpStatus.OK.value()));
            result.setMsg(HttpStatus.OK.getReasonPhrase());
            result.setData(url + "?email=" + email);
        }
        else
        {
            result.setCode(String.valueOf(HttpStatus.NOT_FOUND.value()));
            result.setMsg(HttpStatus.NOT_FOUND.getReasonPhrase());
        }
        return result;
    }

    private String ignoreKeyStringTag(String keyStr)
    {
        StringBuilder sb = new StringBuilder();
        String[] lines = keyStr.split("\n");
        for (String line : lines)
        {
            //忽略秘钥串首尾的标识串
            if (line.charAt(0) != '-')
            {
                sb.append(line).append('\n');
            }
        }
        return sb.toString();
    }

    public boolean verify(String token, String email, String ts)
    {
        String public_Key = ignoreKeyStringTag(publicKey);
        String sign = email + ',' + ts;
        try
        {
            KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
            byte[] encodedKey = base64.decode(public_Key);
            PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
            java.security.Signature signature = java.security.Signature
                    .getInstance(SIGNATURE_ALGORITHM);
            signature.initVerify(pubKey);
            signature.update(sign.getBytes(CHARSET));
            boolean verify = signature.verify(base64.decode(token));
            return verify;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return false;
    }

    public Result checkEmail(String email)
    {
        List<Employee> employeeList = employeeMapper.getEmployeeByEmail(email);
        Result result = new Result();
        if (employeeList.size() == 0)
        {
            result.setCode(String.valueOf(HttpStatus.NOT_FOUND.value()));
            result.setMsg(HttpStatus.NOT_FOUND.getReasonPhrase());
        }
        else
        {
            result.setCode(String.valueOf(HttpStatus.OK.value()));
            result.setMsg(HttpStatus.OK.getReasonPhrase());
            result.setData(url + "?email=" + email);
        }
        return result;
    }
}
